// 文件上传配置接口
export interface FileUploadConfig {
  accept?: string; // 接受的文件类型，如 "image" 或 "all"
  maxSize?: number; // 最大文件大小（MB）
  maxCount?: number; // 最大文件数量
  uploadUrl?: string; // 上传接口地址
  listType?: "text" | "picture" | "picture-card"; // 显示类型
  tips?: string; // 上传提示信息
}

// 选项数据接口
export interface OptionItem {
  value: string;
  text: string;
}

// 表单字段配置接口
export interface FieldConfig {
  key: string;
  label: string;
  type: "input" | "textarea" | "picker" | "datetime" | "date" | "native-date" | "image-upload" | "file-upload" | "attachment-upload" | "readonly" | "department-picker" | "text" | "autocomplete";
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: string[];
  optionsData?: OptionItem[]; // 选项数据
  fileConfig?: FileUploadConfig; // 文件上传配置
  readonly?: boolean; // 只读字段标识
  showInCreate?: boolean; // 是否在新增页面显示
  showInEdit?: boolean; // 是否在编辑页面显示
  showInDetails?: boolean; // 是否在详情页面显示
  popupTitle?: string; // 弹窗标题（用于department-picker类型）
  departmentData?: any[]; // 部门数据（用于department-picker类型）
  // 自动补全相关配置
  searchApi?: (query: string) => Promise<OptionItem[]>; // 自动补全搜索API
  minSearchLength?: number; // 最小搜索长度
  debounceTime?: number; // 防抖时间
  // 原生日期选择器相关属性
  startDate?: string; // 开始日期
  endDate?: string; // 结束日期
  dateFormat?: 'YYYY-MM-DD' | 'YYYY/MM/DD' | 'MM/DD/YYYY'; // 日期格式
  disabled?: boolean; // 是否禁用
  // 数字输入框相关属性
  min?: number; // 最小值
  max?: number; // 最大值
  step?: number | string; // 步长
  precision?: number; // 小数位数
  allowNegative?: boolean; // 是否允许负数
  validation?: (
    value: any,
    formData?: any,
  ) => { valid: boolean; message: string } | true;
}

// 表单分组接口
export interface FormSection {
  key: string;
  title: string;
  fields: FieldConfig[];
}

// 调岗调薪申请单表单配置
export const transferFormConfig: Record<string, FieldConfig> = {
  // 单据信息
  billCode: {
    key: "billCode",
    label: "单据编号",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  billStatus: {
    key: "billStatus",
    label: "单据状态",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: true,
    showInDetails: true,
  },
  remark: {
    key: "remark",
    label: "备注",
    type: "textarea",
    placeholder: "请输入备注信息",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 基本信息
  personId: {
    key: "personId",
    label: "员工",
    type: "autocomplete",
    placeholder: "请输入员工姓名搜索",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
    options: [], // 从API动态获取
    optionsData: [], // 选项数据
    minSearchLength: 1, // 最小搜索长度
    debounceTime: 300, // 防抖时间300ms
  },
  staffNo: {
    key: "staffNo",
    label: "员工工号",
    type: "readonly",
    placeholder: "选择员工后自动填入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  name: {
    key: "name",
    label: "员工姓名",
    type: "readonly",
    placeholder: "选择员工后自动填入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  orgName: {
    key: "orgName",
    label: "公司",
    type: "readonly",
    placeholder: "选择员工后自动填入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  groupName: {
    key: "groupName",
    label: "所属部门",
    type: "readonly",
    placeholder: "选择员工后自动填入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  applyDate: {
    key: "applyDate",
    label: "申请日期",
    type: "native-date",
    placeholder: "请选择申请日期",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  effectiveDate: {
    key: "effectiveDate",
    label: "生效日期",
    type: "native-date",
    placeholder: "请选择生效日期",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  transferType: {
    key: "transferType",
    label: "调整类型",
    type: "picker",
    placeholder: "请选择调整类型",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: [
      "岗位调整",
      "薪资调整",
      "岗位和薪资调整",
      "晋升",
      "降级"
    ],
    optionsData: [
      { value: "岗位调整", text: "岗位调整" },
      { value: "薪资调整", text: "薪资调整" },
      { value: "岗位和薪资调整", text: "岗位和薪资调整" },
      { value: "晋升", text: "晋升" },
      { value: "降级", text: "降级" }
    ],
  },
  transferReason: {
    key: "transferReason",
    label: "调整原因",
    type: "textarea",
    placeholder: "请输入调整原因",
    required: true,
    maxlength: 500,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  supportingDocument: {
    key: "supportingDocument",
    label: "证明文件",
    type: "attachment-upload",
    placeholder: "请上传证明文件",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    fileConfig: {
      accept: "all", // 支持所有文件类型
      maxSize: 10,
      maxCount: 1, // 限制为单文件上传
      listType: "text",
      tips: "支持上传各种格式文件，单个文件不超过10MB"
    }
  },

  // 原职位信息
  originalGroupId: {
    key: "originalGroupId",
    label: "原部门",
    type: "department-picker",
    placeholder: "请选择原部门",
    required: true,
    popupTitle: "选择原部门",
    departmentData: [], // 将通过API动态加载
    optionsData: [], // 选项数据映射
    showInCreate: true,
    showInEdit: true,
    showInDetails: false, // 详情页不显示选择器，只显示名称
  },
  originalGroupName: {
    key: "originalGroupName",
    label: "原部门",
    type: "readonly",
    placeholder: "原部门名称",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  originalPositionId: {
    key: "originalPositionId",
    label: "原岗位",
    type: "picker",
    placeholder: "请选择原岗位",
    required: true,
    options: [],
    optionsData: [],
    disabled: true, // 初始禁用，选择部门后启用
    showInCreate: true,
    showInEdit: true,
    showInDetails: false, // 详情页不显示选择器，只显示名称
  },
  originalPositionName: {
    key: "originalPositionName",
    label: "原岗位",
    type: "readonly",
    placeholder: "原岗位名称",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  originalRank: {
    key: "originalRank",
    label: "原职级",
    type: "input",
    placeholder: "请输入原职级",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  originalBaseSalary: {
    key: "originalBaseSalary",
    label: "原基本薪资",
    type: "input",
    inputType: "number",
    placeholder: "请输入原基本薪资",
    required: true,
    min: 0,
    precision: 2,
    allowNegative: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  originalPositionSalary: {
    key: "originalPositionSalary",
    label: "原岗位薪资",
    type: "input",
    inputType: "number",
    placeholder: "请输入原岗位薪资",
    required: true,
    min: 0,
    precision: 2,
    allowNegative: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  originalPerformanceSalary: {
    key: "originalPerformanceSalary",
    label: "原绩效薪资",
    type: "input",
    inputType: "number",
    placeholder: "请输入原绩效薪资",
    required: true,
    min: 0,
    precision: 2,
    allowNegative: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 调整后信息
  newGroupId: {
    key: "newGroupId",
    label: "新部门",
    type: "department-picker",
    placeholder: "请选择新部门",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false, // 详情页不显示选择器，只显示名称
    popupTitle: "选择新部门",
    departmentData: [], // 部门数据
    options: [], // 从API动态获取
    optionsData: [], // 选项数据
  },
  newGroupName: {
    key: "newGroupName",
    label: "新部门",
    type: "readonly",
    placeholder: "选择新部门后自动填入",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  newJobPositionId: {
    key: "newJobPositionId",
    label: "新岗位",
    type: "picker",
    placeholder: "请先选择新部门",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false, // 详情页不显示选择器，只显示名称
    options: [], // 从API动态获取
    optionsData: [], // 选项数据
    disabled: true, // 默认禁用，选择部门后启用
  },
  newPositionName: {
    key: "newPositionName",
    label: "新岗位",
    type: "readonly",
    placeholder: "选择新岗位后自动填入",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  newRank: {
    key: "newRank",
    label: "新职级",
    type: "input",
    placeholder: "请输入新职级",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  newBaseSalary: {
    key: "newBaseSalary",
    label: "新基本薪资",
    type: "input",
    inputType: "number",
    placeholder: "请输入新基本薪资",
    required: true,
    min: 0,
    precision: 2,
    allowNegative: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  newPositionSalary: {
    key: "newPositionSalary",
    label: "新岗位薪资",
    type: "input",
    inputType: "number",
    placeholder: "请输入新岗位薪资",
    required: false,
    min: 0,
    precision: 2,
    allowNegative: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  newPerformanceSalary: {
    key: "newPerformanceSalary",
    label: "新绩效薪资",
    type: "input",
    inputType: "number",
    placeholder: "请输入新绩效薪资",
    required: true,
    min: 0,
    precision: 2,
    allowNegative: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 工作信息 - 隐藏字段，用于存储数据
  orgId: {
    key: "orgId",
    label: "公司ID",
    type: "input",
    placeholder: "公司ID",
    required: false,
    showInCreate: false,
    showInEdit: false,
    showInDetails: false,
  },
  groupId: {
    key: "groupId",
    label: "部门ID",
    type: "input",
    placeholder: "部门ID",
    required: false,
    showInCreate: false,
    showInEdit: false,
    showInDetails: false,
  },
  group: {
    key: "group",
    label: "公司",
    type: "readonly",
    placeholder: "公司",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 详情页面专用字段
  workflowStatus: {
    key: "workflowStatus",
    label: "工作流状态",
    type: "readonly",
    placeholder: "工作流状态",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approver: {
    key: "approver",
    label: "审批人",
    type: "readonly",
    placeholder: "审批人",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approvalTime: {
    key: "approvalTime",
    label: "审批时间",
    type: "readonly",
    placeholder: "审批时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approvalOpinion: {
    key: "approvalOpinion",
    label: "审批意见",
    type: "readonly",
    placeholder: "审批意见",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
};

// 表单分组配置
export const formSections: FormSection[] = [
  {
    key: "billInfo",
    title: "单据信息",
    fields: [
      transferFormConfig.billCode,
      transferFormConfig.billStatus,
      transferFormConfig.workflowStatus,
      transferFormConfig.remark,
    ],
  },
  {
    key: "transferInfo",
    title: "调动信息",
    fields: [
      transferFormConfig.personId,
      transferFormConfig.staffNo,
      transferFormConfig.name,
      transferFormConfig.applyDate,
      transferFormConfig.effectiveDate,
      transferFormConfig.transferType,
      transferFormConfig.transferReason,
      transferFormConfig.supportingDocument,
    ],
  },
  {
    key: "originalInfo",
    title: "原职位信息（完整信息）",
    fields: [
      transferFormConfig.originalGroupId,
      transferFormConfig.originalPositionId,
      transferFormConfig.originalRank,
      transferFormConfig.originalBaseSalary,
      transferFormConfig.originalPositionSalary,
      transferFormConfig.originalPerformanceSalary,
    ],
  },
  {
    key: "newInfo",
    title: "调整后信息（完整信息）",
    fields: [
      transferFormConfig.newGroupId,
      transferFormConfig.newGroupName,
      transferFormConfig.newJobPositionId,
      transferFormConfig.newPositionName,
      transferFormConfig.newRank,
      transferFormConfig.newBaseSalary,
      transferFormConfig.newPositionSalary,
      transferFormConfig.newPerformanceSalary,
    ],
  },
  {
    key: "workInfo",
    title: "员工信息",
    fields: [
      transferFormConfig.orgName,
      transferFormConfig.groupName,
      transferFormConfig.orgId,
      transferFormConfig.groupId,
    ],
  },
  {
    key: "workflowInfo",
    title: "流程信息",
    fields: [
      transferFormConfig.approver,
      transferFormConfig.approvalTime,
      transferFormConfig.approvalOpinion,
    ],
  },
];

// 根据页面类型过滤表单分组
export const getFormSectionsByPageType = (pageType: 'create' | 'edit' | 'details'): FormSection[] => {
  return formSections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      if (pageType === 'create') {
        return field.showInCreate !== false;
      } else if (pageType === 'edit') {
        return field.showInEdit !== false;
      } else if (pageType === 'details') {
        // 详情页根据showInDetails配置显示字段
        return field.showInDetails !== false;
      }
      return false;
    })
  })).filter(section => section.fields.length > 0);
};

// 根据调整类型动态生成表单分组
export const getDynamicFormSections = (
  transferType: string,
  pageType: 'create' | 'edit' | 'details'
): FormSection[] => {
  // 基础分组
  const billInfoSection = {
    key: "billInfo",
    title: "单据信息",
    fields: [
      transferFormConfig.billCode,
      transferFormConfig.billStatus,
      transferFormConfig.workflowStatus,
      transferFormConfig.remark,
    ],
  };

  const transferInfoSection = {
    key: "transferInfo",
    title: "调动信息",
    fields: [
      transferFormConfig.personId,
      transferFormConfig.staffNo,
      transferFormConfig.name,
      transferFormConfig.applyDate,
      transferFormConfig.effectiveDate,
      transferFormConfig.transferType,
      transferFormConfig.transferReason,
      transferFormConfig.supportingDocument,
    ],
  };

  const workInfoSection = {
    key: "workInfo",
    title: "员工信息",
    fields: [
      transferFormConfig.orgName,
      transferFormConfig.groupName,
      transferFormConfig.orgId,
      transferFormConfig.groupId,
    ],
  };

  // 如果没有选择调整类型，返回基础分组和默认的调整信息分组
  if (!transferType) {
    // 默认的调整信息分组，包含部门和岗位字段
    const defaultNewSection = {
      key: "newInfo",
      title: "调整后信息",
      fields: [
        transferFormConfig.newGroupId,
        transferFormConfig.newGroupName,
        transferFormConfig.newJobPositionId,
        transferFormConfig.newPositionName,
        transferFormConfig.newRank,
        transferFormConfig.newBaseSalary,
        transferFormConfig.newPositionSalary,
        transferFormConfig.newPerformanceSalary,
      ],
    };

    // 工作流信息分组
    const workflowSection = {
      key: "workflowInfo",
      title: "流程信息",
      fields: [
        transferFormConfig.approver,
        transferFormConfig.approvalTime,
        transferFormConfig.approvalOpinion,
      ],
    };

    const allSections = [billInfoSection, transferInfoSection, defaultNewSection, workInfoSection, workflowSection];

    // 根据页面类型过滤字段
    return allSections.map(section => ({
      ...section,
      fields: section.fields.filter(field => {
        if (pageType === 'create') {
          return field.showInCreate !== false;
        } else if (pageType === 'edit') {
          return field.showInEdit !== false;
        } else if (pageType === 'details') {
          return field.showInDetails !== false;
        }
        return false;
      })
    })).filter(section => section.fields.length > 0);
  }

  // 根据调整类型决定原职位信息和调整后信息的分组
  let originalSection: FormSection;
  let newSection: FormSection;

  if (transferType === "岗位调整") {
    // 仅岗位信息
    originalSection = {
      key: "originalInfo",
      title: "原职位信息（仅岗位信息）",
      fields: [
        transferFormConfig.originalGroupId,
        transferFormConfig.originalGroupName,
        transferFormConfig.originalPositionId,
        transferFormConfig.originalPositionName,
        transferFormConfig.originalRank,
      ],
    };
    newSection = {
      key: "newInfo",
      title: "调整后信息（仅岗位信息）",
      fields: [
        transferFormConfig.newGroupId,
        transferFormConfig.newGroupName,
        transferFormConfig.newJobPositionId,
        transferFormConfig.newPositionName,
        transferFormConfig.newRank,
      ],
    };
  } else if (transferType === "薪资调整") {
    // 薪资调整只显示薪资相关字段
    originalSection = {
      key: "originalInfo",
      title: "原职位信息（仅薪资信息）",
      fields: [
        transferFormConfig.originalBaseSalary,
        transferFormConfig.originalPositionSalary,
        transferFormConfig.originalPerformanceSalary,
      ],
    };
    newSection = {
      key: "newInfo",
      title: "调整后信息（仅薪资信息）",
      fields: [
        transferFormConfig.newBaseSalary,
        transferFormConfig.newPositionSalary,
        transferFormConfig.newPerformanceSalary,
      ],
    };
  } else {
    // 岗位和薪资调整、晋升、降级 - 显示所有信息
    originalSection = {
      key: "originalInfo",
      title: "原职位信息（岗位和薪资信息）",
      fields: [
        transferFormConfig.originalGroupId,
        transferFormConfig.originalGroupName,
        transferFormConfig.originalPositionId,
        transferFormConfig.originalPositionName,
        transferFormConfig.originalRank,
        transferFormConfig.originalBaseSalary,
        transferFormConfig.originalPositionSalary,
        transferFormConfig.originalPerformanceSalary,
      ],
    };
    newSection = {
      key: "newInfo",
      title: "调整后信息（岗位和薪资信息）",
      fields: [
        transferFormConfig.newGroupId,
        transferFormConfig.newGroupName,
        transferFormConfig.newJobPositionId,
        transferFormConfig.newPositionName,
        transferFormConfig.newRank,
        transferFormConfig.newBaseSalary,
        transferFormConfig.newPositionSalary,
        transferFormConfig.newPerformanceSalary,
      ],
    };
  }

  // 工作流信息分组
  const workflowSection = {
    key: "workflowInfo",
    title: "流程信息",
    fields: [
      transferFormConfig.approver,
      transferFormConfig.approvalTime,
      transferFormConfig.approvalOpinion,
    ],
  };

  // 组合所有分组 - 正确的顺序：单据信息、调动信息、原职位信息、调整后信息、工作信息、流程信息
  const allSections = [billInfoSection, transferInfoSection, originalSection, newSection, workInfoSection, workflowSection];

  // 根据页面类型过滤字段并设置岗位薪资字段的只读状态
  return allSections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      if (pageType === 'create') {
        return field.showInCreate !== false;
      } else if (pageType === 'edit') {
        return field.showInEdit !== false;
      } else if (pageType === 'details') {
        return field.showInDetails !== false;
      }
      return false;
    }).map(field => {
      // 为岗位薪资字段设置只读状态
      if ((field.key === 'originalPositionSalary' || field.key === 'newPositionSalary') &&
        (transferType === "岗位和薪资调整" || transferType === "晋升" || transferType === "降级")) {
        return {
          ...field,
          readonly: true,
          type: "readonly" as const,
          placeholder: "选择岗位后自动填入"
        };
      }
      return field;
    })
  })).filter(section => section.fields.length > 0);
};

// 表单验证函数
export const validateForm = (
  formData: Record<string, any>,
): { valid: boolean; errors: Record<string, string> } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 遍历所有字段配置
  Object.values(transferFormConfig).forEach((field) => {
    const value = formData[field.key];

    // 必填字段验证
    if (field.required && !value) {
      errors[field.key] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[field.key] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[field.key] = result.message;
        valid = false;
        return;
      }
    }
  });

  return { valid, errors };
};

// 动态表单验证函数 - 根据调整类型和页面类型只验证当前显示的字段
export const validateDynamicForm = (
  formData: Record<string, any>,
  transferType: string,
  pageType: 'create' | 'edit' | 'details'
): { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 获取当前显示的字段
  const currentSections = getDynamicFormSections(transferType, pageType);
  const visibleFields = new Set<string>();

  // 收集所有当前显示的字段
  currentSections.forEach(section => {
    section.fields.forEach(field => {
      visibleFields.add(field.key);
    });
  });

  // 只验证当前显示的字段
  visibleFields.forEach(fieldKey => {
    const field = transferFormConfig[fieldKey];
    if (!field) return;

    const value = formData[fieldKey];

    // 必填字段验证
    if (field.required && (!value || (typeof value === 'string' && value.trim() === ''))) {
      errors[fieldKey] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[fieldKey] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[fieldKey] = result.message;
        valid = false;
        return;
      }
    }
  });

  // 获取第一个错误信息
  const firstError = Object.keys(errors)[0];
  const firstErrorMessage = firstError ? errors[firstError] : undefined;

  return { valid, errors, firstErrorMessage };
};
